package com.pay.service.Impl;

import com.pay.common.pay.constant.Constant;
import com.pay.common.pay.utils.RedisUtils;
import com.pay.common.pay.utils.TokenUtils;
import com.pay.dto.resp.PayMerchantQrCodeRespDTO;
import com.pay.service.PayMerchantQrCodeService;
import com.pay.wechat.config.WxMpConfiguration;
import com.pay.wechat.config.WxMpProperties;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpQrcodeService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * @author zhouyihe
 * @ClassName PayMerchantQrCodeServiceImpl
 * @qq 1552951165
 */
@Service
@Slf4j
public class PayMerchantQrCodeServiceImpl implements PayMerchantQrCodeService {
    @Autowired
    private WxMpProperties wxMpProperties;
    
    @Override
    public PayMerchantQrCodeRespDTO generateQrCode() {
        String appId = wxMpProperties.getConfigs().get(Constant.DEFAULT_VALUE_ZERO).getAppId();
        WxMpQrcodeService qrcodeService = WxMpConfiguration.getMpServices().get(appId).getQrcodeService();
        // 1.生成 二维码对应token
        String sceneIdStr = TokenUtils.getToken();
        try {
            // 2.生成二维码
            WxMpQrCodeTicket wxMpQrCodeTicket = qrcodeService.qrCodeCreateTmpTicket(sceneIdStr, Constant.QRCODE_EXPIRE_SECONDS);
            String url = wxMpQrCodeTicket.getUrl();
            return new PayMerchantQrCodeRespDTO(sceneIdStr, url);
        } catch (Exception e) {
            log.error("e:{}", e);
            return null;
        }
    }
    
    @Override
    public boolean scanningRelevanceOpenId(WxMpXmlMessage wxMpXmlMessage) {
        // 扫码事件处理
        // 1.获取二维码的参数
        String eventKey = wxMpXmlMessage.getEventKey();
        if (eventKey.isEmpty()) {
            return Boolean.FALSE;
        }
        // 2.获取当前用户的openid
        String openId = wxMpXmlMessage.getFromUser();
        // 3.在redis中记录该key用户对应的openId
        RedisUtils.setString(eventKey, openId);
        return Boolean.TRUE;
    }
    
    @Override
    public boolean getQrCodeTokenResult(String qrCodeToken) {
        // 从Redis中获取商家的openid
        String merchantOpenId = RedisUtils.getString(qrCodeToken);
        return !StringUtils.isEmpty(merchantOpenId) ? Boolean.TRUE : Boolean.FALSE;
    }
}
